package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.example.myapplication.model.TUnit;
import com.example.myapplication.until.Adapter_Unit;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 章节列表
 */
public class ChapterActivity extends AppCompatActivity {

    private ListView mListView;
    private List<TUnit> mList = new ArrayList<>();
    int id=1;
    //访问本地接口，用10.0.2.2取代localhost
    private String url = "http://192.168.1.115:8081/DoctorSystem/Unit/getUnitlist?limit=10&page=1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chaptertest);
        mListView = findViewById(R.id.mListView);
    }
    public void onWindowFocusChanged(boolean hasFocus)
    {
        /**
         * 请求数据
         * 解析json
         * 适配器
         * 绑值显示
         */
        if (hasFocus){

            RxVolley.get(url, new HttpCallback() {
                    @Override
                    public void onSuccess(String t) {
                    Toast.makeText(ChapterActivity.this,t,Toast.LENGTH_LONG).show();

                    //控制台输出Json
                    Log.d("aaaa",""+t);

                    //解析json
                    parsingJson(t);


                    Adapter_Unit adapter = new Adapter_Unit(ChapterActivity.this,mList);

                    mListView.setAdapter(adapter);


                }
            });
        }
    }

    //数据解析
    public void parsingJson(String t){
        try {

            JSONObject jsonObject = new JSONObject(t);
            JSONArray jsonList = jsonObject.getJSONArray("data");
            for(int i=0;i<jsonList.length();i++){


                JSONObject json = jsonList.getJSONObject(i);
                int unitid=Integer.parseInt(json.getString("unitid"));
                String unitcode=json.getString("unitcode");
                String unitname=json.getString("unitname");
                // Log.d("zzzz",province);

                mList.add(new TUnit(unitid,unitcode,unitname));

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
